/*
                       _oo0oo_
                      o8888888o
                      88" . "88
                      (| -_- |)
                      0\  =  /0
                    ___/`---'\___
                  .' \\|     |-- '.
                 / \\|||  :  |||-- \
                / _||||| -:- |||||- \
               |   | \\\  -  --/ |   |
               | \_|  ''\---/''  |_/ |
               \  .-\__  '-'  ___/-. /
             ___'. .'  /--.--\  `. .'___
          ."" '<  `.___\_<|>_/___.' >' "".
         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
         \  \ `_.   \_ __\ /__ _/   .-` /  /
     =====`-.____`.___ \_____/___.-`___.-'=====
                       `=---='


     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

               佛祖保佑         永无BUG

 Made by Alex @7/1/2017 8:13 AM

*/
package core

import (
	"bytes"
	"sort"
	"strings"

	"github.com/GeertJohan/go.rice"
	"github.com/huandu/xstrings"
	"github.com/picago/model-generator/xerrros"
)

type ByLength []string

func (s ByLength) Len() int {
	return len(s)
}
func (s ByLength) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s ByLength) Less(i, j int) bool {
	return len(s[i]) > len(s[j])
}

type Tokenizer struct {
	Dict []string
}

func NewTokenizer() Tokenizer {
	dict := loadDict("resource")
	return Tokenizer{Dict: dict}
}

func (tokenizer *Tokenizer) Segment(text string) []string {
	text = strings.ToLower(text)
	words := make([]string, 0, 4)
	for text != "" {
		// 找到字典中的单词
		found := false
		for _, word := range tokenizer.Dict {
			if strings.HasPrefix(text, word) {
				words = append(words, word)
				text = text[len(word):]
				found = true
				break
			}
		}
		// 没有找到,将剩下的部分添加
		if !found {
			words = append(words, text)
			text = ""
		}
	}
	return words
}

func (tokenizer *Tokenizer) ToJavaName(text string) string {
	words := tokenizer.Segment(text)
	var buffer bytes.Buffer
	for idx, word := range words {
		if idx == 0 {
			buffer.WriteString(word)
			continue
		}
		buffer.WriteString(xstrings.ToCamelCase(word))
	}
	return buffer.String()
}

func loadDict(path string) []string {
	box, err := rice.FindBox(path)
	checkError(err)

	data, err := box.String("dict.dat")
	checkError(err)
	lines := xstrings.WordSplit(data)
	sort.Sort(ByLength(lines))
	return lines
}

func checkError(err error) {
	xerrros.PanicIfError(err)
}
